<template>
    <div class="page animate__animated animate__fadeIn">
        <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: '20px 20px' }">
            <el-page-header @back="goBack" content="商品报价"></el-page-header>
        </el-card>
        <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: '20px 20px 20px' }"
            v-loading="loadingPage">
            <el-form size="small" label-width="100px" class="form-con" :model="goodsForm" ref="goodsForm">
                <el-divider content-position="left">商品信息</el-divider>
                <el-form-item label="商品名称" prop="goods_name">
                    <el-input placeholder="请输入商品名称" class="form-input" v-model="goodsForm.goods_name"
                        readonly></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="categoryIds">
                    <!-- <el-cascader v-model="goodsForm.categoryIds" :options="cateGoryList" :props="props" ref="cascader"
                        placeholder="请选择上级分类" class="form-input" disabled></el-cascader> -->
                    <el-input placeholder="请选择上级分类" class="form-input" v-model="levelStr" readonly disabled></el-input>
                </el-form-item>
                <el-form-item label="商品产地" prop="producer">
                    <el-input placeholder="请输入商品产地" class="form-input" v-model="goodsForm.producer" readonly></el-input>
                </el-form-item>
                <!-- <el-divider content-position="left">规格库存</el-divider>
                <el-form-item label="商品规格" props="spec_type">
                    <el-radio-group v-model="goodsForm.spec_type" @input="switchSpec" disabled>
                        <el-radio :label="10">单规格</el-radio>
                        <el-radio :label="20">多规格</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <!-- 单规格 -->
                <div class="single-wrap" v-if="goodsForm.spec_type == 10">
                    <el-form-item label="平台价" prop="goods_price">
                        <el-input v-model="goodsForm.goods_price" class="form-input" placeholder="请输入平台价"
                            readonly></el-input>
                    </el-form-item>
                    <el-form-item label="销售价" prop="market_price">
                        <el-input v-model="goodsForm.market_price" class="form-input" placeholder="请输入销售价"
                            readonly></el-input>
                    </el-form-item>
                    <el-form-item label="库存" prop="stock_num">
                        <el-input v-model="goodsForm.stock_num" class="form-input" placeholder="请输入当前商品库存"
                            readonly></el-input>
                    </el-form-item>
                    <el-form-item label="单位" prop="goods_unit">
                        <el-input v-model="goodsForm.goods_unit" class="form-input" placeholder="请输入单位" readonly
                            v-if="goodsForm.goods_unit"></el-input>
                        <el-input value="暂无" class="form-input" placeholder="请输入单位" readonly v-else></el-input>
                    </el-form-item>
                    <el-form-item label="最低起卖数量" prop="minimum">
                        <el-input v-model="goodsForm.minimum" class="form-input" placeholder="请输入最低起卖数量"
                            readonly></el-input>
                    </el-form-item>
                    <el-form-item label="报价" prop="price">
                        <el-input v-model="goodsForm.price" class="form-input" placeholder="未报价"
                            oninput="value = value.replace(/[^\d|\.]/g, '')"></el-input>
                    </el-form-item>
                </div>
                <!-- 多规格 -->
                <div class="multiple-wrap" v-else>
                    <el-form-item label="SKU列表">
                        <div class="sku-list">
                            <el-table border size="small" header-cell-class-name="header-cell" :data="skuData.skuList"
                                :span-method="spanMethod">
                                <el-table-column :prop="item.prop" :label="item.spec_name" v-for="(
                                            item, index
                                        ) in skuData.specList" :key="index"></el-table-column>
                                <el-table-column prop="image" label="预览图" width="105px">
                                    <template slot-scope="scope">
                                        <el-image style="width: 80px; height: 80px" :src="scope.row.image" fit="contain"
                                            class="sku-img">
                                            <div slot="error" class="image-slot">
                                                <p>暂无图片</p>
                                            </div>
                                        </el-image>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="goods_price" label="平台价" width="160px">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.goods_price" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="market_price" label="销售价" width="160px">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.market_price" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="price" label="报价" width="160px">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.price" placeholder="未报价"
                                            @change="setSpecPrice(scope.$index, $event)"
                                            oninput="value = value.replace(/[^\d|\.]/g, '')"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="stock_num" label="库存数量" width="160px">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.stock_num" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="goods_unit" label="单位" width="160px">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.goods_unit" readonly=""
                                            v-if='scope.row.goods_unit'></el-input>
                                        <el-input value="暂无" readonly="" v-else></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="最低起卖数量">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.minimum" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="goods_sku_no" label="SKU编码">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.goods_sku_no" readonly></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="submitForm()" :disabled="isDisabled"
                        :loading="isLoading">提交</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
<script>
import { goodsQuoList, getGoodsDetail, cateGoryList, goodsQuotation } from "@/api/goods";
import { getLevelData } from '@/utils/util'
import { stringify } from "qs";
export default {
    data() {
        return {
            loadingPage: false,
            goods_id: '',
            company_id: '',
            content: '',
            goodsForm: {
                goods_name: "",
                categoryIds: "",
                producer: "",

                spec_type: 10, // 10 单规格 20 多规格

                //单规格
                goods_price: "0",
                market_price: "0",
                stock_num: "0",
                goods_unit: "",
                minimum: "1",
                price: '',//报价
                goods_sku_id: '',//sku编码
            },
            quotationList: [],
            skuData: {
                specList: [],
                skuList: [],
            },
            cateGoryList: [],
            isDisabled: false,
            isLoading: false,
            props: {
                label: 'name',
                value: 'category_id',
            },
            levelStr: '', // 级联标题
        }
    },
    created() {
        this.goods_id = this.$route.params.id ? this.$route.params.id : "";
        console.log("this.goods_id", this.$route.params);
        this.loadingPage = true;
        this.getGoodsDetail()
    },
    methods: {
        /**
         * getGoodsDetail() 获取商品信息
         * getGoodsQuoList() 查看报价
         * setGoodsData() 设置商品数据
         * getCateGoryList() 获取分类
         * switchSpec 切换规格
         * setMultipleData() 整理规格数据
         * cartesianProductOfSkus() 笛卡尔积算法整合出所有规格的可能性
         * spanMethod() 合并单元行
         */
        getGoodsDetail() {
            getGoodsDetail({
                goods_id: this.goods_id,
                goods_type: 10,
            }).then((res) => {
                this.loadingPage = false;
                if (res.code == 0) {
                    this.setGoodsData(res.data);
                }
            });
        },
        async getGoodsQuoList() {
            return await new Promise((resolve, reject) => {
                goodsQuoList({
                    goods_id: this.goods_id
                }).then(res => {
                    if (res.code == 0) {
                        resolve(res)
                    } else {
                        // reject(err)
                    }
                })
            })
        },
        async setGoodsData(data) {
            // console.log('data', data)
            let quoRes = await this.getGoodsQuoList();
            // console.log('quoRes', quoRes)
            this.company_id = data.company_id;
            this.goodsForm.goods_name = data.goods_name;
            this.goodsForm.categoryIds = data.categoryIds;
            // console.log('categoryIds', data.categoryIds)
            this.goodsForm.producer = data.producer;
            this.goodsForm.spec_type = data.spec_type;
            if (data.spec_type == 10) {
                this.goodsForm.goods_price = data.goods_price;
                this.goodsForm.market_price = data.market_price;
                this.goodsForm.stock_num = data.stock_total;
                this.goodsForm.goods_unit = data.goods_unit;
                this.goodsForm.minimum = data.minimum;
                if (quoRes.data.length > 0) {
                    this.goodsForm.goods_sku_id = quoRes.data[0].sku.id;
                    this.goodsForm.price = quoRes.data[0].price;
                } else {
                    this.goodsForm.goods_sku_id = data.skuList[0].id;
                }
            } else {
                this.setMultipleData(data.specList, data.skuList, quoRes)
            }
            this.getCateGoryList();
        },
        getCateGoryList() {
            cateGoryList({
                status: "-1",
                company_id: this.company_id,
            }).then((res) => {
                this.isLoading = false;
                if (res.code == 0) {
                    // res.data.forEach(v => {
                    //     if (!v.children) {//一级下面没有子元素
                    //         v.disabled = true;
                    //     } else {
                    //         v.children.forEach(item => {
                    //             if (!item.children) {
                    //                 item.disabled = true;
                    //             }
                    //         })
                    //     }
                    // })
                    this.cateGoryList = res.data;
                    const list = this.cateGoryList
                    const ids = this.goodsForm.categoryIds
                    // 获取级联分类
                    this.levelStr = getLevelData(list, ids)
                }
            });
        },
        switchSpec(e) {
            this.goodsForm.spec_type = e;
        },
        matchArrayLength(arr1, arr2) {
            while (arr1.length < arr2.length) {
                arr1.push({
                    price: 0,
                }); // 或者其他你想填充的值
            }
        },
        setMultipleData(specList, skuList, quoRes) {
            let newSkuList = [];
            specList.forEach((v, i) => {
                v.prop = `spec_value_${i}`
            })
            let cartesianList = this.cartesianProductOfSkus(specList),
                newSkuArr = [];
            console.log('quoRes.data', quoRes.data)
            this.matchArrayLength(quoRes.data, skuList)
            console.log('quoRes.data', quoRes.data)
            skuList.forEach((v, i) => {
                if (quoRes.data.length > 0) {
                    v.price = quoRes.data[i].price ? quoRes.data[i].price : '';
                } else {
                    v.price = '';
                }
                const newSkuObj = {
                    ...v,
                    ...cartesianList[i]
                }
                newSkuArr.push(newSkuObj)
            })
            this.skuData.specList = specList;
            this.skuData.skuList = newSkuArr;
            console.log('this.skuData.skuList', this.skuData.skuList)
        },
        cartesianProductOfSkus(skus) {
            function descriptorToObject(descriptor) {
                let attrObj = {};
                let skuKeys = [];
                let skuSelectKeyArr = [];
                let skuKey = "";
                descriptor.forEach((attrValueObj, index) => {
                    var skuKeyObj = {
                        groupKey: attrValueObj.groupKey,
                        valueKey: attrValueObj.key,
                    };
                    var skuSelectKey = attrValueObj.key;
                    skuKeys.push(skuKeyObj);
                    skuSelectKeyArr.push(skuSelectKey);
                    skuKey = skuSelectKeyArr.join("_");
                    attrObj[skus[index].prop] = attrValueObj.spec_value;
                });
                attrObj.skuKeys = skuKeys
                attrObj.skuKey = skuKey
                return attrObj
            }
            function cartesianProduct(a) {
                if (a.length === 0) return [[]];

                let result = [];
                let rest = cartesianProduct(a.slice(1));
                for (let i = 0; i < a[0].length; i++) {
                    for (let j = 0; j < rest.length; j++) {
                        result.push([a[0][i]].concat(rest[j]));
                    }
                }
                return result;
            }
            let descriptors = skus.map((sku) => sku.valueList);
            let combos = cartesianProduct(descriptors);
            return combos.map(descriptorToObject);
        },
        spanMethod({ row, column, rowIndex, columnIndex }) {
            const fields = ["spec_value_0"];
            // 当前行的数据
            const cellValue = row[column.property];
            // 判断只合并定义字段的列数据
            if (cellValue && fields.includes(column.property)) {
                const prevRow = this.skuData.skuList[rowIndex - 1]; //上一行数据
                let nextRow = this.skuData.skuList[rowIndex + 1]; //下一行数据
                // 当上一行的数据等于当前行数据时，当前行单元格隐藏
                if (prevRow && prevRow[column.property] === cellValue) {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    };
                } else {
                    // 反之，则循环判断若下一行数据等于当前行数据，则当前行开始进行合并单元格
                    let countRowspan = 1; //用于合并计数多少单元格
                    while (nextRow && nextRow[column.property] === cellValue) {
                        nextRow =
                            this.skuData.skuList[++countRowspan + rowIndex];
                    }
                    if (countRowspan > 1) {
                        return {
                            rowspan: countRowspan,
                            colspan: 1,
                        };
                    }
                }
            }
        },
        setSpecPrice(index, e) {
            this.skuData.skuList[index].price = e;
        },
        setAjaxData() {
            console.log('this.skuData.skuList', this.skuData.skuList)
            switch (Number(this.goodsForm.spec_type)) {
                case 10:
                    this.quotationList.push({
                        price: this.goodsForm.price,
                        goods_sku_id: this.goodsForm.goods_sku_id
                    })
                    break;
                case 20:
                    this.quotationList = this.skuData.skuList.map(v => {
                        return {
                            price: v.price,
                            goods_sku_id: v.id
                        }
                    })
                    break;
            }
            console.log('this.quotationList', this.quotationList)
        },
        async submitForm() {
            console.log('this.goodsForm', this.goodsForm)
            if (!this.goodsForm.price && this.goodsForm.spec_type == 10) {
                this.$message.error('请填写商品报价');
                return;
            }
            if (this.goodsForm.spec_type == 20) {
                var priceFlag = this.skuData.skuList.every(function (a, b, c) {
                    return a.price != '';
                })
                if (!priceFlag) {
                    this.$message.error('请填写商品报价')
                    return;
                }
            }
            this.isDisabled = true;
            this.isLoading = true;
            this.setAjaxData();
            let res = await this.$getCsrToken();
            if (res.code == 0) {
                goodsQuotation({
                    goods_id: this.goods_id,
                    quotationList: JSON.stringify(this.quotationList)
                }).then(res => {
                    if (res.code == 0) {
                        this.$message.success(res.msg);
                        this.isDisabled = false;
                        this.isLoading = false;
                        setTimeout(() => {
                            this.goBack()
                        }, 1000)
                    } else {
                        this.isDisabled = false;
                        this.isLoading = false;
                    }
                })
            } else {
                this.isDisabled = false;
                this.isLoading = false;
            }
        },
        goBack() {
            this.$router.go(-1);
        },
    }
}
</script>
<style scoped>
/deep/ .el-divider__text {
    font-size: 14px;
    font-weight: bold;
    color: #007bff;
}

.sku-img {
    border-radius: 6px;
}
</style>